package com.mycompany.virtualApp.controller;

import com.mycompany.mvc.utils.BaseResult;
import com.mycompany.mvc.utils.SystemUtil;
import com.mycompany.virtualApp.entity.UpdateApk;
import com.mycompany.virtualApp.service.UpdateApkService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.util.*;

@Controller
@RequestMapping("/updateApk")
public class UpdateApkController {
    Logger logger = LoggerFactory.getLogger(TabAdvController.class);

    @Autowired
    private UpdateApkService updateApkService;
    /**
     * 获取数据
     */
    @RequestMapping("/getUpdateApkList")
    @ResponseBody
    public Map<String,Object> getAllTabAdv(HttpServletRequest request) {

        List<UpdateApk> listTab= new ArrayList<>();
        Map<String,Object> map = new HashMap<>();

        //从第几条数据开始
        int iDisplayStart = Integer.parseInt(request.getParameter("iDisplayStart"));
        //每页显示的记录数
        int iDisplayLength = Integer.parseInt(request.getParameter("iDisplayLength"));
        //点击次数
        int sEcho = Integer.parseInt(request.getParameter("sEcho"));

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("iStart",iDisplayStart);
        paramMap.put("iLength",iDisplayLength);

        try {
            listTab = updateApkService.getUpdateApkList(paramMap);
            List<UpdateApk> listTabAll = updateApkService.getUpdateApkList(new HashMap<>());
            map.put("aData",listTab);
            if(CollectionUtils.isNotEmpty(listTab)){
                map.put("sEcho ",sEcho+1);
                map.put("iTotalDisplayRecords", listTabAll.size());//显示的条数
                map.put("iTotalRecords",listTabAll.size());
            }
        } catch (Exception e) {
            logger.error("升级获取失败!"+e.getMessage());
        }

        return map;
    }

    /**
     *  只保存APK
     */
    @RequestMapping("/saveUpdateApk")
    @ResponseBody
    public BaseResult saveUpdateApk(HttpServletRequest request) {
        BaseResult baseResult = new BaseResult();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile prodPicaFile = multipartRequest.getFile("prodPicaM");
//        MultipartFile prodPicFile = multipartRequest.getFile("prodPic");
        Map<String,Object> prodPicaM = SystemUtil.saveFile(prodPicaFile,multipartRequest);
//        String prodName = multipartRequest.getParameter("prodName");
//        String prodUrl = multipartRequest.getParameter("prodUrl");
//        String prodRadio = multipartRequest.getParameter("prodRadio");

        if(StringUtils.isAnyEmpty(MapUtils.getString(prodPicaM,"savePath"))){
            logger.error("Apk保存失败:图片保存失败!");
            baseResult.setSuccess(false);
            return  baseResult;
        }else{
            //获取软件版本信息
            Map<String,Object> apkMap = SystemUtil.readAPK(MapUtils.getString(prodPicaM,"filePath"));
            //应用名
            String productName = MapUtils.getString(prodPicaM,"productName");
            String packageName = MapUtils.getString(apkMap,"package");
            String versionName = MapUtils.getString(apkMap,"versionName");
            String filePath = MapUtils.getString(prodPicaM,"filePath");
            String versionCodeT = MapUtils.getString(apkMap,"versionCode");
            Integer versionCode = 0;
            if(StringUtils.isNotEmpty(versionCodeT)){
                try {
                    versionCode = Integer.valueOf(versionCodeT);
                } catch (Exception e) {
                    logger.error("versionCode转换异常!"+e.getMessage());
                }
            }
            String url = MapUtils.getString(prodPicaM,"savePath");

            FileInputStream fis= null;
            String md5 = StringUtils.EMPTY;
            try {
                fis = new FileInputStream(filePath);
                md5 = DigestUtils.md5Hex(IOUtils.toByteArray(fis));
            } catch (Exception e) {
                e.printStackTrace();
            }
//            String md5 = SystemUtil.getMd5ByFile(filePath);
//            String versionCode = MapUtils.getString(apkMap,"versionCode");
            logger.info("productName:"+productName+"packageName:"+packageName+"versionName:"+versionName+
            "md5"+md5);
            //MD5 暂时找不到

            logger.info("Apk保存成功:"+prodPicaM);
            baseResult.setSuccess(true);
            Map resultMap = new HashMap();
            resultMap.put("productName",productName);
            resultMap.put("packageName",packageName);
            resultMap.put("versionName",versionName);
            resultMap.put("md5",md5);
            //versionCode隐藏
            resultMap.put("versionCode",versionCode);
            resultMap.put("urlM",url);

            baseResult.setMap(resultMap);
//            baseResult.setCode(prodPicaM);
        }

        return baseResult;
    }

    /**
     *  保存新增的广告
     */
    @RequestMapping("/saveApk")
    @ResponseBody
    public BaseResult saveApk(HttpServletRequest request) {
        BaseResult baseResult = new BaseResult();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//        MultipartFilse prodPicFile = multipartRequest.getFile("prodPic");
//        Map<String,Object> prodPicMap = SystemUtil.saveFile(prodPicFile,multipartRequest);

        String productName = multipartRequest.getParameter("productName");
        String packageName = multipartRequest.getParameter("packageName");
        String versionName = multipartRequest.getParameter("versionName");
        String versionCodeT = multipartRequest.getParameter("versionCode");
        String updateMArea = multipartRequest.getParameter("updateMArea");
        String md5 = multipartRequest.getParameter("md5");

        if(StringUtils.isNotEmpty(productName)){
            String productNameA[] = productName.split(":");
            if(null != productNameA && productNameA.length >0){
                productName = productNameA[1];
            }
        }
        if(StringUtils.isNotEmpty(packageName)){
            String packageNameA[] = packageName.split(":");
            if(null != packageNameA && packageNameA.length >0){
                packageName = packageNameA[1];
            }
        }
        if(StringUtils.isNotEmpty(versionName)){
            String versionNameA[] = versionName.split(":");
            if(null != versionNameA && versionNameA.length >0){
                versionName = versionNameA[1];
            }
        }
        if(StringUtils.isNotEmpty(md5)){
            String md5A[] = md5.split(":");
            if(null != md5A && md5A.length >0){
                md5 = md5A[1];
            }
        }

        Integer versionCode = 0;
        if(StringUtils.isNotEmpty(versionCodeT)){
            try {
                versionCode = Integer.valueOf(versionCodeT);
            } catch (Exception e) {
                logger.error("versionCode转换异常!"+e.getMessage());
            }
        }

        String url = multipartRequest.getParameter("urlM");

//        if(StringUtils.isAnyEmpty(prodPic,prodName,prodUrl,prodRadio)){
//            logger.error(msg+"广告保存失败:图片保存失败!");
//            baseResult.setSuccess(false);
//            return  baseResult;
//        }

        UpdateApk updateApk = new UpdateApk();
        updateApk.setApkName(productName);
        updateApk.setPackageName(packageName);
        updateApk.setVersionCode(versionCode);
        updateApk.setVersionName(versionName);
        updateApk.setMd5(md5);
//        updateApk.setUpdateTime(new Date());
        updateApk.setUrl(url);
        updateApk.setDes(updateMArea);
        updateApk.setCreateTime(new Date());
        updateApk.setUpdateTime(new Date());
        updateApk.setDel_flag(0);

        try {
            updateApkService.saveUpdateApk(updateApk);
            //更改字典表，全局显示majt
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("UpdateApk保存失败:数据库插入失败!");
            baseResult.setSuccess(false);
            return  baseResult;
        }

        baseResult.setSuccess(true);
        return baseResult;
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public BaseResult delete(HttpServletRequest request) {
        BaseResult baseResult = new BaseResult();
        String id = request.getParameter("id");

        Map<String,Object> map = new HashMap<>();
        map.put("id",id);

        try {
            updateApkService.delete(map);
            baseResult.setSuccess(true);
            return baseResult;
        } catch (Exception e) {
            logger.error("updateApk删除失败");
            baseResult.setSuccess(false);
        }

        return baseResult;
    }

    /**
     *  获取单个广告信息
     */
    @RequestMapping("/editMId")
    @ResponseBody
    public BaseResult<UpdateApk> editMId(HttpServletRequest request, @RequestParam Integer id) {
        BaseResult<UpdateApk> baseResult = new BaseResult();

        Map<String,Object> map = new HashMap<>();
        map.put("id",id);

        try {
            //新增一个查询语句
            List<UpdateApk> updateApkList = updateApkService.getUpdateApkList(map);
            if(CollectionUtils.isNotEmpty(updateApkList)){
                UpdateApk updateApk = updateApkList.get(0);
                baseResult.setSuccess(true);
                baseResult.setT(updateApk);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("编辑Apk失败!");
            baseResult.setSuccess(false);
            return baseResult;
        }
        return baseResult;
    }

    /**
     *  更新单个广告信息
     */
    @RequestMapping("/editApk")
    @ResponseBody
    public BaseResult<UpdateApk> editApk(HttpServletRequest request, @RequestParam Integer id) {
        BaseResult<UpdateApk> baseResult = new BaseResult();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//        MultipartFile prodPicaFile = multipartRequest.getFile("prodPica");
//        MultipartFile prodPicFile = multipartRequest.getFile("prodPic");
//        Map<String,Object> prodPicMap = SystemUtil.saveFile(prodPicFile,multipartRequest);
//        String prodPic = MapUtils.getString(prodPicMap,"savePath");
//        String prodName = multipartRequest.getParameter("prodName");
//        String prodUrl = multipartRequest.getParameter("prodUrl");
//        String prodRadio = multipartRequest.getParameter("prodRadio");

        String productName = multipartRequest.getParameter("productName");
        String packageName = multipartRequest.getParameter("packageName");
        String versionName = multipartRequest.getParameter("versionName");
        String versionCodeT = multipartRequest.getParameter("versionCode");
        String updateMArea = multipartRequest.getParameter("updateMArea");
        String ids = request.getParameter("idAPk");
        if(StringUtils.isNotEmpty(ids)){
            id = Integer.valueOf(ids);
        }
        if(StringUtils.isNotEmpty(productName)){
            String productNameA[] = productName.split(":");
            if(null != productNameA && productNameA.length >0){
                productName = productNameA[1];
            }
        }
        if(StringUtils.isNotEmpty(packageName)){
            String packageNameA[] = packageName.split(":");
            if(null != packageNameA && packageNameA.length >0){
                packageName = packageNameA[1];
            }
        }
        if(StringUtils.isNotEmpty(versionName)){
            String versionNameA[] = versionName.split(":");
            if(null != versionNameA && versionNameA.length >0){
                versionName = versionNameA[1];
            }
        }

        Integer versionCode = 0;
        if(StringUtils.isNotEmpty(versionCodeT)){
            try {
                versionCode = Integer.valueOf(versionCodeT);
            } catch (Exception e) {
                logger.error("versionCode转换异常!"+e.getMessage());
            }
        }

        String md5 = multipartRequest.getParameter("md5");
        String url = multipartRequest.getParameter("urlM");

//        if(StringUtils.isAnyEmpty(prodPic,prodName,prodUrl,prodRadio)){
//            logger.error(msg+"广告保存失败:图片保存失败!");
//            baseResult.setSuccess(false);
//            return  baseResult;
//        }

        UpdateApk updateApk = new UpdateApk();
        updateApk.setId(id);
        updateApk.setApkName(productName);
        updateApk.setPackageName(packageName);
        updateApk.setVersionCode(versionCode);
        updateApk.setVersionName(versionName);
        updateApk.setMd5(md5);
//        updateApk.setUpdateTime(new Date());
        updateApk.setUrl(url);
        updateApk.setDes(updateMArea);
        updateApk.setUpdateTime(new Date());
        updateApk.setDel_flag(0);

        try {
            updateApkService.updateUpdateApk(updateApk);
            baseResult.setSuccess(true);
            return baseResult;
        } catch (Exception e) {
            logger.error("updateApk更新失败");
            baseResult.setSuccess(false);
        }
        return baseResult;
    }
}
